package cz.cvut.manatee.processManager;

import java.rmi.RemoteException;

public class QueryRMIImplement implements QueryRMI {
	/*
	 * Reference na pridelovac dotazu
	 */
	protected static Assigner assigner;
	
	protected static int timeout = 60000;

	public static void setTimeout(int timeout) {
		QueryRMIImplement.timeout = timeout;
	}

	public static void setAssigner(Assigner assigner) {
		QueryRMIImplement.assigner = assigner;
	}
	
	public Result solveQuery(Query dotaz) {
		synchronized (dotaz) {
			try {
				assigner.addQueryToQueue(dotaz);
			} catch (ProcessManagerException e) {
				Logging.get().severe("Dotaz se nepodarilo vlozit do fronty dotazu: "+e);
				return new ErrorResult("ProcessManager RMI: Dotaz se nepodarilo vlozit do fronty dotazu.: "+e);
			}
			
			try {
				dotaz.wait(timeout); // ceka dokud se obsuzne vlakno nevypocte vysledek. Po vypocteni vlakno vola notify   
			} catch (InterruptedException e) {
				Logging.get().severe("Pri cekani na vysledek bylo prijato preruseni.");
				return new ErrorResult("ProcessManager RMI: Pri cekani na vysledek bylo prijato preruseni.");
			}
		}
		
		
		if (dotaz.isStateSolved()) {
			Result vysledek = dotaz.getResult();
			try {
				assigner.removeQueryFromQueue(dotaz);
			} catch (ProcessManagerException e) {
				Logging.get().severe("Dotaz byl bezpecne odebiran, ale nebyl ve stavu SOLVED.");
				return new ErrorResult("ProcessManager RMI: Dotaz byl bezpecne odebiran, ale nebyl ve stavu SOLVED.");
			}
			return vysledek;
		} else {
			assigner.removeQueryFromQueueForce(dotaz);
			Logging.get().severe("Odebiram dotaz z fronty, ktery neni vyresen.");
			return new ErrorResult("ProcessManager RMI: Odebiram dotaz z fronty, ktery neni vyresen.");
		}
	}
	
	public Result Concordance(String corpusName, String CQL, int maxline, String leftContext, String rightContext, String kwica, String ctxa, String struca, String refa, int maxctx, boolean useview) throws RemoteException {
		ConcordanceQuery dotaz = new ConcordanceQuery(corpusName, CQL, maxline, leftContext, rightContext, kwica, ctxa, struca, refa, maxctx, useview);
		Result vysledek = this.solveQuery(dotaz);
		return vysledek;
	}
	
	public Result Concordance(String corpusName, String CQL, int maxline, String leftContext, String rightContext, String kwica, String ctxa, String struca, String refa, int maxctx) throws RemoteException {
		ConcordanceQuery dotaz = new ConcordanceQuery(corpusName, CQL, maxline, leftContext, rightContext, kwica, ctxa, struca, refa, maxctx);
		Result vysledek = this.solveQuery(dotaz);
		return vysledek;
	}
	
	public Result CollocationQuery(String corpusName, String CQL, String attr_name, char sort_fun_code, long minfreq, long minbgr, int fromw, int tow, int maxitems) throws RemoteException {
		CollocationQuery dotaz = new CollocationQuery(corpusName, CQL, attr_name, sort_fun_code, minfreq, minbgr, fromw, tow, maxitems);
		Result vysledek = this.solveQuery(dotaz);
		return vysledek;
	}

}
